package com.hqyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hqyj.dao.UserInfoDao;
import com.hqyj.exception.UserInfoException;
import com.hqyj.pojo.UserInfo;
import com.hqyj.service.UserInfoService;
import com.hqyj.utile.JwtUtil;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 项目:demo-springboot-230701
 * 描述:
 * 时间:2023/9/26 10:42
 * 作者:admin
 * 版本:1.0
 **/
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoDao,UserInfo> implements UserInfoService {

     //注入短信发送服务类
    @Autowired
    SmsClient smsClient;
     //注入邮件发送服务类
    @Autowired
     JavaMailSender javaMailSender;
    //注入dao
    @Resource
    UserInfoDao userInfoDao;

    @Value("${spring.mail.username}")
    private String email;
    @Override
    public HashMap<String, Object> add(UserInfo userInfo) throws UserInfoException {
        HashMap<String, Object> map = null;
        try {
            map = new HashMap<String, Object>();
            int num = userInfoDao.insert(userInfo);
            log.info("ID:{}",userInfo.getUserId());
            if(num > 0){
                map.put("msg","插入成功");
                map.put("code",200);
            }else{
                map.put("msg","插入失败");
                map.put("code",500);
            }
        } catch (Exception e) {
            //e.printStackTrace();
            throw new UserInfoException(e.getMessage(),"插入失败",e.getMessage(),500);
        }
        return map;
    }

    @Override
    public HashMap<String, Object> update(UserInfo userInfo) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        int num = userInfoDao.updateById(userInfo);

        if(num > 0){
            map.put("msg","修改成功");
            map.put("code",200);
        }else{
            map.put("msg","修改失败");
            map.put("code",500);
        }
        return map;
    }

    @Override
    public HashMap<String, Object> del(Integer id) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        int num = userInfoDao.deleteById(id);
        if(num > 0){
            map.put("msg","删除成功");
            map.put("code",200);
        }else{
            map.put("msg","删除失败");
            map.put("code",500);
        }
        return map;
    }

    @Override
    public HashMap<String, Object> search(UserInfo userInfo) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //根据用户名查询
        QueryWrapper<UserInfo> query = new QueryWrapper<>();
        query.eq("user_name",userInfo.getUserName());
        List<UserInfo> list  = userInfoDao.selectList(query);
        map.put("list",list);
        return map;
    }

    @Override
    public HashMap<String, Object> addBitch(List<UserInfo> list) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        boolean is = this.saveBatch(list);
        if(is){
            map.put("msg","批量插入成功");
            map.put("code",200);
        }else{
            map.put("msg","批量插入失败");
            map.put("code",500);
        }
        return map;
    }

    @Override
    public HashMap<String, Object> updateBitch(List<UserInfo> list) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        boolean is = this.updateBatchById(list);
        if(is){
            map.put("msg","批量修改成功");
            map.put("code",200);
        }else{
            map.put("msg","批量修改失败");
            map.put("code",500);
        }
        return map;
    }

    @Override
    public HashMap<String, Object> delBitch(List<Integer> list) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        int num = userInfoDao.deleteBatchIds(list);
        if(num > 0){
            map.put("msg","批量删除成功");
            map.put("code",200);
        }else{
            map.put("msg","批量删除失败");
            map.put("code",500);
        }
        return map;
    }

    @Override
    public HashMap<String, Object> searchBitch(List<Integer> list) {
        HashMap<String, Object> map = new HashMap<String, Object>();

        List<UserInfo> lis  = userInfoDao.selectBatchIds(list);
        map.put("list",lis);
        return map;
    }

    @Override
    public HashMap<String, Object> searchByCondition(UserInfo userInfo) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //创建查询构造器
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        //定义id查询条件
        boolean is = userInfo.getUserId()!=null;
        queryWrapper.eq(is,"user_id",userInfo.getUserId());
        //定义userName条件查询
        boolean iss = userInfo.getUserName()!=null&&!userInfo.getUserName().equals("");
        queryWrapper.like(iss,"user_name",userInfo.getUserName());
        //定义userDetailId
        boolean isss = userInfo.getUserDetailId()!=null;

        queryWrapper.gt(isss,"user_detail_id",userInfo.getUserDetailId());
        //查询
        List<UserInfo> list = userInfoDao.selectList(queryWrapper);
        map.put("list",list);

        return map;
    }

    @Override
    public HashMap<String, Object> searchPage(UserInfo userInfo) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //1 创建分页对象
        Page<UserInfo> page = new Page<>(userInfo.getPage(),userInfo.getRow());
        //2 查询结果，获取分页结果对象
        Page<UserInfo> userInfoPage = userInfoDao.selectPage(page,null);

        //当前页集合
        map.put("list",userInfoPage.getRecords());
        //总条数
        map.put("total",userInfoPage.getTotal());
        //总页数
        map.put("totalPage",userInfoPage.getPages());
        return map;
    }

    @Override
    public HashMap<String, Object> emailSend(String toEmail, String title, String content) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        try {
            //创建一个邮件对象
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            //定义收件人
            simpleMailMessage.setTo(toEmail);
            //发件人
            simpleMailMessage.setFrom(email);
            //标题
            simpleMailMessage.setSubject(title);
            //邮件正文
            simpleMailMessage.setText(content);
            //发送邮件
            javaMailSender.send(simpleMailMessage);
            log.info("发送成功");
        } catch (MailException e) {
            e.printStackTrace();
            log.info("发送失败");
        }

        return map;

    }

    @Override
    public HashMap<String, Object> smsSend(String tel) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        try {
            //创建短信发送对象
            SendSmsRequest request = new SendSmsRequest();
            //接收人电话
            String[] phones ={tel};
            request.setPhoneNumberSet(phones);
            //短信模版ID
            request.setTemplateId("1259138");
            //短信发送SDK
            request.setSmsSdkAppId("1400372925");
            //短信签名
            request.setSignName("阳光云公众号");
            //短信验证码
            Random rd = new Random();
            int num = rd.nextInt(10000);
            String[] code = {num+""};
            request.setTemplateParamSet(code);
            //发送短信，获取短信响应对象
            SendSmsResponse response = smsClient.SendSms(request);
            String info = SendSmsResponse.toJsonString(response);
            log.info("响应信息{}",info);
            //把info字符串转换成java类对象
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                Map<String,Object> m = objectMapper.readValue(info,Map.class);

                List<HashMap<String,Object>> list =( List<HashMap<String,Object>>)m.get("SendStatusSet");
                if(list.get(0).get("Code").equals("Ok")){
                    log.info("短信发送成功");
                    map.put("msg","短信发送成功");
                    map.put("code",200);
                }

            } catch (JsonProcessingException e) {
                log.info("短信发送失败");
                map.put("msg","短信发送失败");
                map.put("code",500);
                e.printStackTrace();
            }

        } catch (TencentCloudSDKException e) {
            log.info("短信发送失败");
            map.put("msg","短信发送失败");
            map.put("code",500);
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public HashMap<String, Object> login(UserInfo userInfo) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //假设登录成功
        //1  用户id
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userInfo.getUserName());
        UserInfo u = userInfoDao.selectOne(queryWrapper);
        //2 生产token
        String token = JwtUtil.createUserToken(u.getUserId()+"",u.getUserName(),u.getUserSalt());
        map.put("token",token);
        map.put("code",200);
        return map;
    }


}
